package com.itheima.sh;

import com.itheima.sh.mapper.UserMapper;
import com.itheima.sh.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserMapper userMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping
    public List<User> findAll() {

        // 1 查询缓存
        List userList = redisTemplate.opsForList().range("users", 0L, -1L);
        if (!userList.isEmpty()) {
            return userList;
        }
        // 2 缓存中不存在则，查询数据库
        List<User> users = userMapper.findAll();
        
        // 3 查询到后存到缓存中
        if (users.size() > 0) {
            redisTemplate.opsForList().leftPushAll("users", users);
        }
       
        return users;
    }

}